#!/bin/bash
# containerd 1.4.4 https://github.com/containerd/containerd
# runc 1.0.0-rc93 https://github.com/opencontainers/runc
# cri-tools 1.21.0 https://github.com/kubernetes-sigs/cri-tools

CRI_TOOLS_VERSION="1.21.0"
CONTAINERD_VERSION="1.4.4"
RUNC_VERSION="1.0.0-rc93"

echo "downloading binaries..."
wget --timestamping \
  https://github.com/opencontainers/runc/releases/download/v${RUNC_VERSION}/runc.amd64 \
  https://github.com/containerd/containerd/releases/download/v${CONTAINERD_VERSION}/containerd-${CONTAINERD_VERSION}-linux-amd64.tar.gz \
  https://github.com/kubernetes-sigs/cri-tools/releases/download/v${CRI_TOOLS_VERSION}/crictl-v${CRI_TOOLS_VERSION}-linux-amd64.tar.gz

echo "download complete..."

echo "processing to /usr/local/bin/..."
mv runc.amd64 runc
tar -xvf crictl-v${CRI_TOOLS_VERSION}-linux-amd64.tar.gz
chmod +x crictl runc
mv crictl runc /usr/local/bin/

mkdir ./containerd
tar -xvf containerd-${CONTAINERD_VERSION}-linux-amd64.tar.gz -C ./containerd
mv ./containerd/bin/* /usr/local/bin/

# clean junk files
rm -rf ./containerd
rm -f containerd-${CONTAINERD_VERSION}-linux-amd64.tar.gz
rm -f crictl-v${CRI_TOOLS_VERSION}-linux-amd64.tar.gz

echo "processing complete..."


echo "start configuration..."
mkdir -p /etc/containerd/

cat << EOF | tee /etc/containerd/config.toml
[plugins]
  [plugins.cri.containerd]
    snapshotter = "overlayfs"
    [plugins.cri.containerd.default_runtime]
      runtime_type = "io.containerd.runtime.v1.linux"
      runtime_engine = "/usr/local/bin/runc"
      runtime_root = ""
    [plugins."io.containerd.grpc.v1.cri".registry]
      [plugins."io.containerd.grpc.v1.cri".registry.mirrors]
        [plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"]
          endpoint = ["https://0emkhxpp.mirror.aliyuncs.com"]
    [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
      [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
        SystemdCgroup = true
EOF

cat << EOF | tee /etc/systemd/system/containerd.service
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target

[Service]
ExecStartPre=/sbin/modprobe overlay
ExecStart=/usr/local/bin/containerd
Restart=always
RestartSec=5
Delegate=yes
KillMode=process
OOMScoreAdjust=-999
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity

[Install]
WantedBy=multi-user.target
EOF

crictl config runtime-endpoint unix:///var/run/containerd/containerd.sock

echo "configuration complete..."

systemctl daemon-reload
systemctl enable containerd
systemctl start containerd

echo "app started..."
